const interceptor = ($provide, $httpProvider, $locationProvider, APP_CONFIG) => {
    const httpInterceptor = ($rootScope, $q) => {
        return {
            request(config) {
                var url = config.url, 
                    m = /\.[^?]+/g.exec(url), subfix;
                if (m && (subfix = m[0]) && config.cache && subfix.toLowerCase() == '.jhtml') {
                    config.cache = undefined;
                }
                return config;
            },
            requestError(response) {
                return $q.reject(response);
            },
            response(response) {
                return response.config.headers.appid == APP_CONFIG.appid ? ((response.data && 200 == response.data.code) ? response.data : $q.reject(response)) : response;
            },
            responseError(response) {
                if (response.status === 403) {
                    $rootScope.$emit("userIntercepted", "notLogin", response);
                    return response;
                } else if (response.status === 404) {
                    $rootScope.$emit("error404", "404", response);
                    return response;
                } else if (response.status === 401) {
                    $rootScope.$emit("accessDenied", "forbidden", response);
                    return response;
                } else if (response.status === 500) {
                    $rootScope.$emit("error500", "500", response);
                    return response;
                }
                return $q.reject(response);
            }
        };
    }
    httpInterceptor.$inject = ['$rootScope', '$q'];

    $provide.factory('ErrorHttpInterceptor', httpInterceptor);

    $httpProvider.interceptors.push('ErrorHttpInterceptor');
}
interceptor.$inject = ['$provide', '$httpProvider', '$locationProvider', 'APP_CONFIG']

export default interceptor